package com.xsoft.navigation.pdr;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

/**
 * created by zhangkai on 2021/8/2
 * email: 405547628@qq.com
 * desc:
 */
public class StepDetectionHandler implements SensorEventListener {
    private SensorManager sensorManager;
    private Sensor sensor;
    private StepDetectionListener stepDetectionListener;
    private int step = 0;

    public StepDetectionHandler(SensorManager sensorManager) {
        this.sensorManager = sensorManager;
        sensor = this.sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
    }

    public void start() {
        sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    public void stop() {
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        Log.i("zhang", "onSensorChanged");
        float y;
        if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
            y = event.values[1];
            Log.i("zhang", "onSensorChanged y = " + y);
            // seuil  partir duquel on considre qu'il s'agit bien d'un pas
            if (y > 1 && stepDetectionListener != null) {
                onNewStepDetected();

            }
        }
    }

    public void onNewStepDetected() {
        float distanceStep = 0.8f;
        step++;
        stepDetectionListener.newStep(distanceStep);
    }

    public void setStepListener(StepDetectionListener listener) {
        stepDetectionListener = listener;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public interface StepDetectionListener {
        void newStep(float stepSize);
    }
}
